package com.dgut.utils;

import org.apache.poi.hssf.usermodel.*;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class ExcelUtil {
    public static HSSFWorkbook getHSSFWorkbook(String sheetName, List<String> titles,List<List<String>>values){
        //创建excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        //创建sheet表
        HSSFSheet sheet = wb.createSheet(sheetName);
        HSSFRow row = sheet.createRow(0);
        //单元格的样式
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //声明单元格
        HSSFCell cell = null;
        //写入标题
        for(int i=0;i<titles.size();i++){
            cell = row.createCell(i);
            cell.setCellValue(titles.get(i));
            cell.setCellStyle(style);
        }
        //写入内容
        if(!values.isEmpty()){
            for(int i=0; i<values.size();i++){
                row = sheet.createRow(i+1);
                for(int j=0;j<values.get(i).size();j++){
                    cell = row.createCell(j);
                    cell.setCellStyle(style);
                    cell.setCellValue(values.get(i).get(j));
                }
            }
        }
        return wb;
    }

    /**
     *
     * @param sheet 表
     * @param size  列数
     */
    //设置列宽自适应
    public static void setSizeColumn(HSSFSheet sheet, int size){
        for (int columnNum=0; columnNum <size; columnNum++){
            int columnWidth = sheet.getColumnWidth(columnNum)/256;
            for(int rowNum=0; rowNum<sheet.getLastRowNum();rowNum++){
                HSSFRow currentRow;
                //没有一行
                if(sheet.getRow(rowNum)==null){
                    currentRow = sheet.createRow(rowNum);
                }else{
                    currentRow =sheet.getRow(rowNum);
                }
                if(currentRow.getCell(columnNum)!=null){
                    HSSFCell currentCell = currentRow.getCell(columnNum);
                    int length = currentCell.getStringCellValue().getBytes().length;
                    if(columnNum<length){
                        columnWidth = length;
                    }
                }
            }
            sheet.setColumnWidth(columnNum,columnWidth*256);
        }
    }
}
